<template>
  <el-dialog v-model="visible" :title="`${paramsProps.title}`" :destroy-on-close="true" width="580px" draggable>
    <el-form
      ref="ruleFormRef"
      label-width="140px"
      label-suffix=" :"
      :rules="rules"
      :model="paramsProps.row"
      @submit.enter.prevent="handleSubmit"
    >
      <el-form-item label="DTU设备编号" prop="dtuNumber">
        <el-input v-model="paramsProps.row.dtuNumber" placeholder="请填写DTU设备编号" clearable></el-input>
      </el-form-item>
      <el-form-item label="设备名称" prop="name">
        <el-input v-model="paramsProps.row.name" placeholder="请填写设备名称" clearable></el-input>
      </el-form-item>
      <!-- <el-form-item label="排序" prop="sort">
        <el-input-number v-model="paramsProps.row.sort" :precision="0" :min="1" :max="999999" />
      </el-form-item> -->
      <el-form-item label="端口" prop="port">
        <el-input-number v-model="paramsProps.row.port" :min="1" :max="65535" controls-position="right" placeholder="请输入端口号" />
      </el-form-item>
      <el-form-item label="ICCID" prop="iccid">
        <el-input v-model="paramsProps.row.iccid" placeholder="请填写ICCID" clearable></el-input>
      </el-form-item>
      <el-form-item label="LEDID" prop="ledid">
        <el-input v-model="paramsProps.row.ledid" placeholder="请填写LEDID" clearable></el-input>
      </el-form-item>
      <!-- <el-form-item label="绑定密码" prop="bindToken">
        <el-input v-model="paramsProps.row.bindToken" placeholder="请填写绑定密码" clearable></el-input>
      </el-form-item>
      <el-form-item label="设备状态 （字典表dtu_status）" prop="dtuStatus">
        <el-select v-model="paramsProps.row.dtuStatus" clearable placeholder="请选择设备状态 （字典表dtu_status）">
          <el-option
            v-for="item in optionsStore.getDictOptions('dtu_status')"
            :key="item.id"
            :label="item.codeName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="绑定时间" prop="bindTime">
        <el-date-picker clearable
          v-model="paramsProps.row.bindTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="请选择绑定时间">
        </el-date-picker>
      </el-form-item> -->
      <el-form-item label="过期时间" prop="expireTime">
        <el-date-picker
          clearable
          v-model="paramsProps.row.expireTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="请选择过期时间"
        >
        </el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="绑定车辆" prop="vehicleId">
        <el-select v-model="paramsProps.row.vehicleId" clearable placeholder="请选择车辆">
          <el-option
            v-for="item in optionsStore.getDictOptions('')"
            :key="item.id"
            :label="item.codeName"
            :value="item.id"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="绑定车辆" prop="vehicleId">
        <el-tree-select
          v-model="paramsProps.row.vehicleId"
          :data="VehicleInfoList"
          check-strictly
          placeholder="请选择车辆"
          :render-after-expand="false"
          clearable
          :default-expand-all="true"
          :props="VehicleInfoProps"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false"> 取消</el-button>
      <el-button type="primary" @click="handleSubmit"> 确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { type ElForm, ElMessage } from 'element-plus';
import { useOptionsStore } from '@/stores/modules/options';
import type { VehicleInfoRow } from '@/api/types/vehicleinfo/vehicleInfo';
import { getVehicleInfoListNopApi } from '@/api/modules/vehicleinfo/vehicleInfo';

defineOptions({
  name: 'DtuInfoForm'
});

const optionsStore = useOptionsStore();

const VehicleInfoList = ref<VehicleInfoRow[]>([]);
// const VehicleInfoProps = {
//   label: 'vehicleNumber',
//   value: 'id'
// };
const VehicleInfoProps = {
  value: 'id',
  label: (data: VehicleInfoRow) => {
    // 添加类型安全检查
    const deptName = (data as any).fullDeptName || '';
    return `${deptName} -- ${data.vehicleNumber}`;
  }
};

const rules = reactive({
  dtuNumber: [{ required: true, message: '请填写DTU设备编号' }],
  name: [{ required: false, message: '请填写设备名称' }],
  sort: [{ required: true, message: '请填写排序' }],
  iccid: [{ required: false, message: '请填写ICCID' }],
  ledid: [{ required: false, message: '请填写LEDID' }],
  bindToken: [{ required: true, message: '请填写绑定密码' }],
  dtuStatus: [{ required: true, message: '请填写设备状态 （字典表dtu_status）' }],
  bindTime: [{ required: true, message: '请填写绑定时间' }],
  expireTime: [{ required: false, message: '请填写过期时间' }],
  delFlag: [{ required: true, message: '请填写是否删除' }],
  vehicleId: [{ required: false, message: '请填写车辆id' }],
  port: [{ required: false, message: '请填写端口号' }]
});

const visible = ref(false);
const paramsProps = ref<View.DefaultParams>({
  title: '',
  row: {},
  api: undefined,
  getTableList: undefined
});

// 接收父组件传过来的参数
const acceptParams = (params: View.DefaultParams) => {
  paramsProps.value = params;
  visible.value = true;
  loadVehicleInfo();
};
const loadVehicleInfo = () => {
  getVehicleInfoListNopApi({}).then(res => {
    // 确保res.data是数组
    VehicleInfoList.value = Array.isArray(res.data) ? res.data : [res.data];
  });
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<InstanceType<typeof ElForm>>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      await paramsProps.value.api!(paramsProps.value.row);
      ElMessage.success({ message: `${paramsProps.value.title}成功！` });
      paramsProps.value.getTableList!();
      visible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

defineExpose({
  acceptParams
});
</script>

<style scoped lang="scss"></style>